<template>
  <div class="cartbox">
    <ServeModel />

    <!-- 购物车列表 -->
    <van-checkbox-group v-model="result">
      <van-checkbox
        :name="item.id"
        v-for="item in cartList"
        :key="item.id"
        @click="goodsItemClick(item)"
        :disabled="isEditing"
      >
        <van-swipe-cell>
          <van-card
            :num="item.number"
            :price="item.retail_price"
            desc="描述信息"
            :title="item.goods_name"
            :thumb="item.list_pic_url"
          />
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="del(item.product_id)"
            />
          </template>
        </van-swipe-cell>
        <!-- 步进器 -->
        <van-stepper
          v-model="item.number"
          v-show="isEditing"
          @change="changeNum(item)"
        />
      </van-checkbox>
    </van-checkbox-group>

    <!-- 提交订单栏 -->
    <van-submit-bar
      :price="cartTotal.checkedGoodsAmount * 100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checkedAll" :disabled="isEditing || cartList === 0"
        >全选</van-checkbox
      >
      <template #tip>
        累计共{{ cartTotal.goodsCount }}件商品，可点击
        <van-button
          :type="isEditing ? 'danger' : 'primary'"
          size="small"
          @click="isEditing = !isEditing"
          >{{ isEditing ? "完成编辑" : "编辑" }}</van-button
        >
        按钮进行商品数量修改
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import ServeModel from "@/components/ServeModel";
import Vue from "vue";
import {
  GetCartData,
  getCheckedData,
  SetStepNumData,
  DelgoodsData,
} from "@/request/api";
export default {
  data() {
    return {
      result: [],
      checked: "",
      cartList: [],
      cartTotal: "",
      isEditing: false,
    };
  },
  components: {
    ServeModel,
  },
  methods: {
    renderData(res) {
      this.result = [];
      let { cartList, cartTotal } = res.data;
      this.cartList = cartList;
      this.cartTotal = cartTotal;
      this.cartList.map((item) => {
        item.checked ? this.result.push(item.id) : "";
      });
    },
    onSubmit() {},

    // 点击步进器对数据进行请求刷新操作
    changeNum(item) {
      SetStepNumData({
        goodsId: item.goods_id,
        id: item.id,
        number: item.number,
        productId: item.product_id,
      }).then((res) => {
        console.log("步进器", res);
        this.renderData(res);
      });
    },

    // 执行删除操作
    del(id) {
      DelgoodsData({
        productIds: id.toString(),
      }).then((res) => {
        this.renderData(res);
      });
    },

    // 点击小复选框发起请求
    goodsItemClick(item) {
      // 判断是否在编辑状态
      if (this.isEditing) return;
      getCheckedData({
        isChecked: item.checked == 1 ? "0" : "1",
        productIds: item.product_id.toString(),
      }).then((res) => {
        console.log("点击了商品的res", res);
        // 拿到数据之后需要重新渲染数据（渲染产品列表数据和产品列表每一项的勾选状态）
        this.renderData(res);
        // console.log("点击时result的值：", this.result);
      });
    },
  },
  created() {
    GetCartData().then((res) => {
      // console.log(res.data);
      this.renderData(res);

      // console.log("第一次进来时result的值：", this.result);
    });
  },
  computed: {
    checkedAll: {
      get() {
        return (
          this.result.length == this.cartList.length &&
          this.cartList.length != 0
        );
      },
      set(newVal) {
        // 判断是否在编辑状态
        if (this.isEditing) return;
        let ids = this.cartList.map((item) => {
          return item.product_id;
        });

        // 发起全选/全不选的请求
        getCheckedData({
          // 判断改变的值决定修改isChecked的值
          isChecked: newVal == false ? "0" : "1",
          productIds: ids.join(),
        }).then((res) => {
          // 拿到数据之后需要重新渲染数据（渲染产品列表数据和产品列表每一项的勾选状态）
          this.renderData(res);
        });
      },
    },
  },

  //   组件内部的路由守卫
  //   只有点击当前页面时才执行这里的代码
  beforeRouteEnter(to, from, next) {
    //   理解：比全局的写法更好，不用每次跳转路由都去进行判断
    // 不！能！获取组件实例、
    // 因为当守卫之前前，组件实例还没被创建
    let token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      Vue.prototype.$toast("请先登录");
      // 拿不到token，说明没有登录，跳转到我的页面登录
      setTimeout(() => {
        next("/user");
      }, 800);
    }
  },
};
</script> 
 
<style lang = "less" scoped>
/* .cartbox {
  padding-bottom: 1rem;
} */
.van-checkbox-group {
  background-color: #fff;
  padding: 0.1rem;
  /deep/.van-checkbox__label {
    flex: 1;
  }
}
.van-submit-bar {
  bottom: 0.5rem;
}
.van-submit-bar {
  text-align: center;

  /deep/.van-submit-bar__tip {
    align-items: center;
  }
}
.van-stepper {
  text-align: right;
}
.delete-button {
  height: 100%;
}
</style>